package com.uniledger.exchange;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.king.zxing.Intents;
import com.uniledger.commonlib.lazy.LazyViewPager;
import com.uniledger.commonlib.util.DisplayUtil;
import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.commonlib.util.URLParser;
import com.uniledger.exchange.base.activity.BaseActivity;
import com.uniledger.exchange.dapp.AndroidBug5497Workaround;
import com.uniledger.exchange.dapp.OnDappListener;
import com.uniledger.exchange.event.GuideEvent;
import com.uniledger.exchange.home.HomeFragment;
import com.uniledger.exchange.home.MainAdapter;
import com.uniledger.exchange.home.scheme.TransferActivity;
import com.uniledger.exchange.mine.MineFragment;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.model.StellarAsset;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxSchedulers;
import com.uniledger.exchange.wallet.WalletKey;

import org.greenrobot.eventbus.EventBus;
import org.stellar.sdk.KeyPair;

import java.util.List;

import butterknife.BindString;
import butterknife.BindView;
import io.github.novacrypto.bip39.SeedCalculator;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.pushy.sdk.Pushy;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 应用主页，应用入口Activity
 */
public class HomeActivity extends BaseActivity implements
        BottomNavigationBar.OnTabSelectedListener,
        ViewPager.OnPageChangeListener,
        EasyPermissions.PermissionCallbacks,
        OnDappListener {

    /**
     * 文件存储权限
     */
    private static final String[] READ_AND_WRITE_STORAGE =
            {Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private static final int RC_READ_AND_WRITE_STORAGE = 124;

    @BindView(R.id.label_net_error)
    TextView label_net_error;

    @BindView(R.id.bottom_navigation_bar)
    BottomNavigationBar bottomNavigationBar;

    @BindView(R.id.viewPager)
    LazyViewPager viewPager;

    @BindString(R.string.main_bottom_bar_home)
    String barHome;
    @BindString(R.string.main_bottom_bar_shopping)
    String barShop;
    @BindString(R.string.main_bottom_bar_me)
    String barMine;
    @BindString(R.string.main_bottom_bar_dapp)
    String barDapp;

    @BindView(R.id.bar_title)
    TextView barTitle;

    @BindView(R.id.bar_back)
    AppCompatImageView dappBack;

    @BindView(R.id.bar_forward)
    AppCompatImageView dappForward;

    @BindView(R.id.bar_home)
    AppCompatImageView dappHome;

    public void setBar(boolean isDapp, String title) {
        int flag = isDapp ? View.VISIBLE : View.GONE;
        dappBack.setVisibility(flag);
        dappForward.setVisibility(flag);
        dappHome.setVisibility(flag);

        barTitle.setText(title);
    }

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, HomeActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initViewPager();
        push();
        EventBus.getDefault().post(new GuideEvent());

        AndroidBug5497Workaround.assistActivity(this, DisplayUtil.dip2px(this, 58));

        if (OkSingleton.getInstance().getSourceKeyPair() == null) {
            UniApp.getDb().keyDao().loadKey(123)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<WalletKey>() {
                        @Override
                        public void accept(WalletKey walletKey) throws Exception {
                            //助记词+口令
                            final byte[] seed = new SeedCalculator().calculateSeed(walletKey.mnemonic, "");
                            KeyPair keyPair = KeyPair.fromSecretSeed(seed);
                            OkSingleton.getInstance().setSourceKeyPair(keyPair);
                        }
                    });
        }
    }

    @Override
    public void initBar() {
        super.initBar();
        if (toolbar == null) return;
        setBar(false, barHome);
        ((MenuBuilder) toolbar.getMenu()).setOptionalIconsVisible(true);
        initBottomNavigationBar();

    }

    /**
     * 初始化VP
     */
    private void initViewPager() {
        viewPager.setOnPageChangeListener(this);
        MainAdapter mainAdapter = new MainAdapter(getSupportFragmentManager());
        viewPager.setAdapter(mainAdapter); //视图加载适配器
    }

    /**
     * 初始化底部导航栏
     */
    private void initBottomNavigationBar() {
        bottomNavigationBar.setTabSelectedListener(this);
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
        bottomNavigationBar.setBarBackgroundColor(R.color.navigationBarColor);

        BottomNavigationItem homeItem = new BottomNavigationItem(R.drawable.ic_bottom_bar_home_press, barHome);
        homeItem.setInactiveIconResource(R.drawable.ic_bottom_bar_home);

        BottomNavigationItem dappItem = new BottomNavigationItem(R.drawable.ic_bottom_bar_shop_press, barDapp);
        dappItem.setInactiveIconResource(R.drawable.ic_bottom_bar_shop);

//        BottomNavigationItem shopItem = new BottomNavigationItem(R.drawable.ic_bottom_bar_shop_press, barShop);
//        shopItem.setInactiveIconResource(R.drawable.ic_bottom_bar_shop);

        BottomNavigationItem mineItem = new BottomNavigationItem(R.drawable.ic_bottom_bar_mine_press, barMine);
        mineItem.setInactiveIconResource(R.drawable.ic_bottom_bar_mine);

        bottomNavigationBar
                .addItem(homeItem)
                .addItem(dappItem)
//                .addItem(shopItem)
                .addItem(mineItem)
                .setFirstSelectedPosition(0)
                .initialise(); //所有的设置需在调用该方法前完成
    }

    /**
     * 初始化参数
     */
    @Override
    public void getParams() {

    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int position) {
        //ViewPager滑动
        bottomNavigationBar.selectTab(position);
        //设置切换标题
        switch (position) {
            case 1:
                setBar(true, barDapp);
                break;
            case 2:
                setBar(false, barMine);
                break;
            default:
                setBar(false, barHome);
                break;
        }
    }


    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onTabSelected(int position) {
        //tab被选中
        viewPager.setCurrentItem(position, false);
//        invalidateOptionsMenu();
    }

    @Override
    public void onTabUnselected(int position) {

    }

    @Override
    public void onTabReselected(int position) {

    }

    /**
     * 创建菜单栏
     *
     * @param menu
     * @return
     */
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_home, menu);
//        return true;
//    }

    /**
     * 菜单栏的动态更新切换
     *
     * @param menu
     * @return
     */
//    @Override
//    public boolean onPrepareOptionsMenu(Menu menu) {
//        switch (viewPager.getCurrentItem()) {
//            case 1: //Dapp 浏览器
//                menu.findItem(R.id.item_menu_more).setVisible(false);
//                menu.findItem(R.id.item_menu_shop).setVisible(false);
//                break;
//            case 2://商店页面
//                menu.findItem(R.id.item_menu_more).setVisible(false);
//                menu.findItem(R.id.item_menu_shop).setVisible(true);
//                break;
//            case 3://个人主页
//                menu.findItem(R.id.item_menu_more).setVisible(true);
//                menu.findItem(R.id.item_menu_shop).setVisible(false);
//                break;
//            default://首页
//                menu.findItem(R.id.item_menu_more).setVisible(true);
//                menu.findItem(R.id.item_menu_shop).setVisible(false);
//                break;
//        }
//
//        return super.onPrepareOptionsMenu(menu);
//    }

    /**
     * 菜单栏事件监听
     *
     * @param
     * @return
     */
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.item_menu_more:
//                Toast.makeText(this, "我是第一个", Toast.LENGTH_SHORT).show();
//                break;
//            case R.id.item_menu_shop:
//                Toast.makeText(this, "我是第二个", Toast.LENGTH_SHORT).show();
//                break;
//            default:
//                break;
//        }
//        return true;
//    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == HomeFragment.REQUEST_SCANNER_CODE
                && resultCode == RESULT_OK) {  //扫码识别结果
            parseCode(data);
        } else if (requestCode == MineFragment.REQUEST_CODE_OUT && resultCode == RESULT_OK) {
            GuideActivity.start(HomeActivity.this);
            finish();
        }
    }

    public void parseCode(Intent data) {
        String result = data.getStringExtra(Intents.Scan.RESULT);
        //TODO
        if (!TextUtils.isEmpty(result)) {

            if (!result.contains("http")) {//判断是否包含HTTP协议
                result = BuildConfig.API_HOST + result;
            }

            //参数解析
            URLParser urlParser = URLParser.fromURL(result);

            //读取收款码付款信息
            Api.getService().willPay(urlParser.getParameter("paycode"))
                    .compose(RxSchedulers.io_main())
                    .subscribe(new Consumer<HttpResult<StellarAsset>>() {
                        @Override
                        public void accept(HttpResult<StellarAsset> httpResult) throws Exception {
                            TransferActivity.start(HomeActivity.this, httpResult.data);
                        }
                    }, new RxException<>(new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            //TODO 扫码错误解析处理
                        }
                    }));
        }
    }

    /**
     * 推送权限获取,监听
     */
    @AfterPermissionGranted(RC_READ_AND_WRITE_STORAGE)
    void push() {
        if (hasReadAndWritePermissions()) {
            Pushy.listen(HomeActivity.this);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.permissions_storage),
                    RC_READ_AND_WRITE_STORAGE,
                    READ_AND_WRITE_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 判断是否有读写文件夹权限
     *
     * @return
     */
    private boolean hasReadAndWritePermissions() {
        return EasyPermissions.hasPermissions(HomeActivity.this, READ_AND_WRITE_STORAGE);
    }

    /**
     * 授权成功
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
//        ToastUtils.show("权限授予成功");
    }

    /**
     * 授权拒绝操作
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public AppCompatImageView getDappBack() {
        return dappBack;
    }

    @Override
    public AppCompatImageView getDappForward() {
        return dappForward;
    }

    @Override
    public AppCompatImageView getDappHome() {
        return dappHome;
    }

    @Override
    public void setDappTitle(String title) {

    }

    @Override
    public void onChangeListener(int netMobile) {
        this.netType = netMobile;
        if (!isNetConnect()) {
            label_net_error.setVisibility(View.VISIBLE);
        } else {
            label_net_error.setVisibility(View.GONE);
        }
    }
}
